import { System, World } from '@ecs/index'
import { createScene } from '../entities'
import { Rotate, Velocity } from '../components'

/**
 * 事件系统
 * @description 游戏点击事件
 */
export class EventSystem extends System {
  constructor(
    private readonly canvas: HTMLCanvasElement,
    private readonly world: World
  ) {
    super()
    this.canvas.addEventListener('touchstart', this.onClickCanvas)
    this.canvas.addEventListener('click', this.onClickCanvas)
  }

  public update(): void {}

  public destory(): void {
    this.canvas.removeEventListener('touchstart', this.onClickCanvas)
    this.canvas.removeEventListener('click', this.onClickCanvas)
  }

  /**
   * 点击canvas绘图区域
   * @param e event事件对象
   * @returns 无
   */
  private onClickCanvas = (e: TouchEvent | MouseEvent): void => {
    e.preventDefault()
    if (this.world.data.isGameOver === true) {
      // 游戏结束
      this.world.resetEntity()
      createScene(this.world)
      this.world.data.isGameOver = false
      this.world.start()
    } else {
      // 游戏进行
      const brid = this.world.findNameWithEntities('brid')[0]
      if (!brid) {
        return
      }
      const componentMap = this.world.findEntityWithComponents(brid)
      const velocity = componentMap.get(Velocity)
      const rotate = componentMap.get(Rotate)
      velocity.vy = -5
      rotate.va = -0.1
    }
  }
}
